package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    public static final String APP_INFO_ARTICLE = "app_info_article";

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    EsService<SearchArticleVO> esService;


    @Autowired
    ApUserSearchService apUserSearchService;


    /**ES文章分页搜索功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //参数检查
        String searchWords = dto.getSearchWords();
        if(searchWords==null|| StringUtils.isBlank(searchWords)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if(user!=null) dto.setEntryId(user.getId());

        apUserSearchService.insert(dto);

        //构建查询条件执行查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建查询条件和过滤
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键词查询
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", searchWords);
        boolQueryBuilder.must(queryBuilder);
        //查询小于  mindata的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);
        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());
        //按照发布时间倒叙
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //高亮内容(搜索的内容)
        highlightBuilder.field("title");
        //前置标签
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        //后置标签
        highlightBuilder.postTags("</font>");
        //设置高亮条件
        searchSourceBuilder.highlighter(highlightBuilder);
        //添加查询条件
        searchSourceBuilder.query(boolQueryBuilder);
        PageResponseResult searchResult = esService.search(searchSourceBuilder, SearchArticleVO.class, APP_INFO_ARTICLE);
        //返回结果休要拼接minion 文章的前缀路径
        List<SearchArticleVO> list =(List<SearchArticleVO>)searchResult.getData();
        //判断list是否为空
        if(CollectionUtils.isNotEmpty(list)){
            //遍历集合
            for (SearchArticleVO searchArticleVO : list) {
                //添加前缀路径
                searchArticleVO.setStaticUrl(readPath+searchArticleVO.getStaticUrl());
            }

        }
        return searchResult;
    }

    /**添加索引文章
     *
     * @param article
     */
    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,APP_INFO_ARTICLE);
    }

    /**删除索引文章
     *
     * @param articleId
     */
    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,APP_INFO_ARTICLE);
    }
}
